package server;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.*;

public class OutTermProcesser {

    Map<String,Set<String>> mapJiwai = new HashMap<>();

    public void index(String indexContentPath) throws Exception{
        try {
            String line = "";
            File file = new File(indexContentPath);
            if(file.exists()){
                File[] files = file.listFiles();
                for (File oneFile : files){
                    String nodeName = oneFile.getName();
                    InputStreamReader inputStreamReader= new InputStreamReader(new FileInputStream(oneFile),"utf-8");
                    BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
                    while ((line = bufferedReader.readLine()) != null){
                        String userInput = line.replaceAll("[\\pP\\p{Punct}]","").toLowerCase();
                        if (!mapJiwai.containsKey(line)) {
                            Set<String> nodeSet = new HashSet<>();
                            nodeSet.add(nodeName);
                            mapJiwai.put(userInput, nodeSet);
                        } else {
                            Set<String> tmpSet = mapJiwai.get(userInput);
                            tmpSet.add(nodeName);
                            mapJiwai.put(userInput, tmpSet);
                        }
                    }
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    //只要大于0.95的都会匹配到，返回多个结果
    public Map<String,Double> search(String queryStr,float nDistancePercentage){

        Map<String,Double> similarResults = new HashMap<>();
        try {
            String tar = queryStr.replaceAll("[\\pP\\p{Punct}]", "");
            SimilarityUtils similarityUtils = new SimilarityUtils();

            for (Map.Entry<String,Set<String>> entry : mapJiwai.entrySet()){
                String src = entry.getKey();
                double accu = similarityUtils.similarity(src, tar);
                if (accu > nDistancePercentage) {
                    Set<String> similarRes = entry.getValue();
                    if (similarRes.size()> 0) {
                        for (String re : similarRes){//若有多个结果
                            similarResults.put(re, accu);
                        }
                    }
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }

        return similarResults;
    }

}
